﻿using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Furion;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using Furion.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using PMP.Core.Entities;
using PMP.Core.Extensions;
using PMP.Core.SqlSugar;

namespace PMP.Web.Core;


/// <summary>
/// 异常处理
/// </summary>
public class LogExceptionHandler : IGlobalExceptionHandler, ISingleton
{

    public async Task OnExceptionAsync(ExceptionContext context)
    {
        //请求参数
        var param = "";
        if (context.HttpContext.Request.Method == "GET")
        {
            param = context.HttpContext.Request.QueryString.Value;
        }
        else if (context.HttpContext.Request.Method == "POST")
        {
            context.HttpContext.Request.EnableBuffering();//启用倒带, 读取request.body里的的参数, 还必须在在Program.cs里也启用倒带功能
            context.HttpContext.Request.Body.Position = 0;
            using var reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8);
            param = await reader.ReadToEndAsync();
        }

        Log.Error($"请求接口：{context.HttpContext.Request.Path}{Environment.NewLine}请求参数:{param}{Environment.NewLine}",context.Exception);
        var exceptionLog = new SysExceptionLog
        {
            LogLevel = LogLevel.Error,
            Message = context.Exception.Message.Substring(0,Math.Min(context.Exception.Message.Length,400)),
            StackTrace = context.Exception.StackTrace?.Substring(0,Math.Min(context.Exception.StackTrace.Length,4000)),
            RequestUrl = context.HttpContext.Request.Path,
            RequestBody = param?.Substring(0, Math.Min(param.Length,4000)),
            OperatorId = App.User.GetUserId()
        };

        await DbContext.Instance.Insertable(exceptionLog).ExecuteCommandAsync();
    }
}